<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="任务名称" prop="syncName">
        <el-input
          v-model="queryParams.syncName"
          placeholder="请输入同步任务名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="同步任务状态" clearable>
          <el-option
            v-for="dict in dict.type.sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:dbsync:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:dbsync:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:dbsync:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-video-play"
          size="mini"
          :disabled="single"
          @click="handleSync"
          v-hasPermi="['system:dbsync:run']"
        >执行同步</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="dbSyncList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="syncId" />
      <el-table-column label="同步任务名称" align="center" prop="syncName" :show-overflow-tooltip="true" />
      <el-table-column label="源数据库" align="center" prop="sourceDb" :show-overflow-tooltip="true" />
      <el-table-column label="目标数据库" align="center" prop="targetDb" :show-overflow-tooltip="true" />
      <el-table-column label="同步类型" align="center" prop="syncType" width="100">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.syncType === '0'">全量</el-tag>
          <el-tag type="success" v-else-if="scope.row.syncType === '1'">增量</el-tag>
          <el-tag type="warning" v-else>未知</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="执行计划" align="center" prop="cronExpression" />
      <el-table-column label="最后同步时间" align="center" prop="lastSyncTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.lastSyncTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:dbsync:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:dbsync:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-video-play"
            @click="handleSync(scope.row)"
            v-hasPermi="['system:dbsync:run']"
          >执行</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-tickets"
            @click="handleLog(scope.row)"
            v-hasPermi="['system:dbsync:log']"
          >日志</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改数据库同步对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="780px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="任务名称" prop="syncName">
              <el-input v-model="form.syncName" placeholder="请输入同步任务名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="同步类型" prop="syncType">
              <el-radio-group v-model="form.syncType">
                <el-radio label="0">全量</el-radio>
                <el-radio label="1">增量</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="源数据库" prop="sourceDb">
              <el-select v-model="form.sourceDb" placeholder="请选择源数据库" @change="getSourceTables">
                <el-option
                  v-for="db in sourceDbOptions"
                  :key="db.value"
                  :label="db.label"
                  :value="db.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="目标数据库" prop="targetDb">
              <el-select v-model="form.targetDb" placeholder="请选择目标数据库">
                <el-option
                  v-for="db in targetDbOptions"
                  :key="db.value"
                  :label="db.label"
                  :value="db.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="同步表" prop="syncTables">
          <el-transfer
            v-model="form.syncTables"
            :data="tableOptions"
            :titles="['可选表', '已选表']"
            :props="{
              key: 'value',
              label: 'label'
            }"
          ></el-transfer>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="执行计划" prop="cronExpression">
              <el-input v-model="form.cronExpression" placeholder="请输入Cron表达式" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in dict.type.sys_normal_disable"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDbSync, getDbSync, delDbSync, addDbSync, updateDbSync, runDbSync, getDbList, getTablesByDb } from "@/api/system/dbsync";

export default {
  name: "DatabaseSync",
  dicts: ['sys_normal_disable'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 数据库同步表格数据
      dbSyncList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 表格数据
      tableOptions: [],
      // 源数据库选项
      sourceDbOptions: [],
      // 目标数据库选项
      targetDbOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        syncName: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        syncName: [
          { required: true, message: "同步任务名称不能为空", trigger: "blur" }
        ],
        sourceDb: [
          { required: true, message: "源数据库不能为空", trigger: "change" }
        ],
        targetDb: [
          { required: true, message: "目标数据库不能为空", trigger: "change" }
        ],
        syncType: [
          { required: true, message: "同步类型不能为空", trigger: "change" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getDbOptions();
  },
  methods: {
    /** 查询数据库同步列表 */
    getList() {
      this.loading = true;
      listDbSync(this.queryParams).then(response => {
        this.dbSyncList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 获取数据库列表 */
    getDbOptions() {
      getDbList().then(response => {
        this.sourceDbOptions = response.data;
        this.targetDbOptions = response.data;
      });
    },
    /** 获取源数据库表列表 */
    getSourceTables() {
      if (this.form.sourceDb) {
        getTablesByDb(this.form.sourceDb).then(response => {
          this.tableOptions = response.data;
        });
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        syncId: undefined,
        syncName: undefined,
        sourceDb: undefined,
        targetDb: undefined,
        syncType: "0",
        syncTables: [],
        cronExpression: undefined,
        status: "0",
        remark: undefined
      };
      this.resetForm("form");
      this.tableOptions = [];
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.syncId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加数据库同步任务";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const syncId = row.syncId || this.ids;
      getDbSync(syncId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改数据库同步任务";
        this.getSourceTables();
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.syncId != undefined) {
            updateDbSync(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDbSync(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const syncIds = row.syncId || this.ids;
      this.$modal.confirm('是否确认删除数据库同步任务编号为"' + syncIds + '"的数据项？').then(function() {
        return delDbSync(syncIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 执行同步按钮操作 */
    handleSync(row) {
      const syncId = row.syncId || this.ids;
      this.$modal.confirm('是否确认执行数据库同步任务"' + row.syncName + '"？').then(function() {
        return runDbSync(syncId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("同步任务执行成功");
      }).catch(() => {});
    },
    /** 查看日志按钮 */
    handleLog(row) {
      this.$router.push({
        path: '/datasync/database/log',
        query: {
          syncId: row.syncId
        }
      });
    }
  }
};
</script> 